package com.biao.mall.order.web;

import com.biao.common.exception.NoStockException;
import com.biao.mall.order.config.ThreadLocalConfig;
import com.biao.mall.order.service.OrderService;
import com.biao.mall.order.vo.OrderConfirmVo;
import com.biao.mall.order.vo.OrderSubmitVo;
import com.biao.mall.order.vo.SubmitOrderResponseVo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import static com.biao.mall.order.constant.OrderConstant.USER_ORDER_TOKEN_PREFIX;

@Controller
public class OrderWebController {


    @Autowired
    OrderService orderService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    StringRedisTemplate redisTemplate;

    @GetMapping("/toTrade")
    public String toTrade(Model model, HttpServletRequest request) throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = orderService.confirmOrder();
        //防止重复下单使用token（验证码方式）
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(USER_ORDER_TOKEN_PREFIX + ThreadLocalConfig.get().getId().toString(), token, 30, TimeUnit.MINUTES);
        confirmVo.setToken(token);
        model.addAttribute("orderConfirmData", confirmVo);
        return "confirm";
    }

    /**
     * 下单功能
     *
     * @return
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo vo, Model model, RedirectAttributes redirectAttributes) {
        try {
            SubmitOrderResponseVo responseVo = orderService.submitOrder(vo);
            if (responseVo.getCode() == 0) {
                model.addAttribute("submitOrderResp", responseVo);
                return "pay";
            } else {
                String msg = "下单失败";
                switch (responseVo.getCode()) {
                    case 1:
                        msg += "订单信息过期，请刷新重新提交";
                        break;
                    case 2:
                        msg += "订单商品价格发生变化，请确认后再次提交";
                        break;
                    case 3:
                        msg += "商品库存不足";
                }
                redirectAttributes.addFlashAttribute("msg", msg);
                return "redirect:http://order.mall.com/toTrade";
            }
        } catch (Exception e) {
            e.printStackTrace();
          if (e instanceof NoStockException){
              redirectAttributes.addFlashAttribute("msg", "商品库存不足");
              return "redirect:http://order.mall.com/toTrade";
          }
            redirectAttributes.addFlashAttribute("msg", "未知错误");
            return "redirect:http://order.mall.com/toTrade";
        }
    }
}